<template>
  <Sidebar ref="sidebarRef" :title="$t('setting.title')" width="300">
    <div class="sidebarContent" :class="{ isDark }">
      <div class="title noTop">{{ $t('setting.watermark') }}</div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.showWatermark') }}</span>
          <el-switch
            v-model="watermarkConfig.show"
            @change="watermarkShowChange"
          ></el-switch>
        </div>
      </div>
      <div class="row" v-if="watermarkConfig.show">
        <div class="rowItem">
          <span class="name">{{ $t('setting.watermarkText') }}</span>
          <el-input
            v-model="watermarkConfig.text"
            size="small"
            @input="updateWatermarkConfig"
          ></el-input>
        </div>
      </div>
      <div class="row" v-if="watermarkConfig.show">
        <div class="rowItem">
          <span class="name">{{ $t('setting.watermarkLineSpacing') }}</span>
          <el-input-number
            v-model="watermarkConfig.lineSpacing"
            size="small"
            :min="0"
            @change="updateWatermarkConfig"
          ></el-input-number>
        </div>
      </div>
      <div class="row" v-if="watermarkConfig.show">
        <div class="rowItem">
          <span class="name">{{ $t('setting.watermarkTextSpacing') }}</span>
          <el-input-number
            v-model="watermarkConfig.textSpacing"
            size="small"
            :min="0"
            @change="updateWatermarkConfig"
          ></el-input-number>
        </div>
      </div>
      <div class="row" v-if="watermarkConfig.show">
        <div class="rowItem">
          <span class="name">{{ $t('setting.watermarkAngle') }}</span>
          <el-input-number
            v-model="watermarkConfig.angle"
            size="small"
            :min="0"
            :max="360"
            @change="updateWatermarkConfig"
          ></el-input-number>
        </div>
      </div>
      <div class="row" v-if="watermarkConfig.show">
        <div class="rowItem">
          <span class="name">{{ $t('setting.watermarkColor') }}</span>
          <Color
            :color="watermarkConfig.textStyle.color"
            @change="
              color => {
                watermarkConfig.textStyle.color = color
                updateWatermarkConfig()
              }
            "
          ></Color>
        </div>
      </div>
      <div class="row" v-if="watermarkConfig.show">
        <div class="rowItem">
          <span class="name">{{ $t('setting.watermarkOpacity') }}</span>
          <el-input-number
            v-model="watermarkConfig.textStyle.opacity"
            size="small"
            :min="0"
            :max="1"
            :step="0.1"
            @change="updateWatermarkConfig"
          ></el-input-number>
        </div>
      </div>
      <div class="row" v-if="watermarkConfig.show">
        <div class="rowItem">
          <span class="name">{{ $t('setting.watermarkFontSize') }}</span>
          <el-input-number
            v-model="watermarkConfig.textStyle.fontSize"
            size="small"
            :min="12"
            @change="updateWatermarkConfig"
          ></el-input-number>
        </div>
      </div>
      <div class="row" v-if="watermarkConfig.show">
        <div class="rowItem">
          <span class="name">{{ $t('setting.onlyExport') }}</span>
          <el-switch
            v-model="watermarkConfig.onlyExport"
            @change="updateWatermarkConfig"
          ></el-switch>
        </div>
      </div>

      <!-- <div class="title">{{ $t('setting.other') }}</div> -->
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.openPerformance') }}</span>
          <el-switch
            v-model="config.openPerformance"
            @change="
              value => {
                updateOtherConfig('openPerformance', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.enableFreeDrag') }}</span>
          <el-switch
            v-model="config.enableFreeDrag"
            @change="
              value => {
                updateOtherConfig('enableFreeDrag', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <!-- <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.enableNodeRichText') }}</span>
          <el-switch
            v-model="enableNodeRichText"
            @change="enableNodeRichTextChange"
          ></el-switch>
        </div>
      </div> -->
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.isShowScrollbar') }}</span>
          <el-switch
            v-model="localConfigs.isShowScrollbar"
            @change="
              value => {
                updateLocalConfig('isShowScrollbar', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.alwaysShowExpandBtn') }}</span>
          <el-switch
            v-model="config.alwaysShowExpandBtn"
            @change="
              value => {
                updateOtherConfig('alwaysShowExpandBtn', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.enableAutoEnterTextEditWhenKeydown') }}</span>
          <el-switch
            v-model="config.enableAutoEnterTextEditWhenKeydown"
            @change="
              value => {
                updateOtherConfig('enableAutoEnterTextEditWhenKeydown', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.enableDragImport') }}</span>
          <el-switch
            v-model="localConfigs.enableDragImport"
            @change="
              value => {
                updateLocalConfig('enableDragImport', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.enableInheritAncestorLineStyle') }}</span>
          <el-switch
            v-model="config.enableInheritAncestorLineStyle"
            @change="
              value => {
                updateOtherConfig('enableInheritAncestorLineStyle', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.enableAi') }}</span>
          <el-switch
            v-model="localConfigs.enableAi"
            @change="
              value => {
                updateLocalConfig('enableAi', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.mousewheelAction') }}</span>
          <el-select
            v-model="config.mousewheelAction"
            size="small"
            @change="
              value => {
                updateOtherConfig('mousewheelAction', value)
              }
            "
          >
            <el-option
              v-for="item in mousewheelActionList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="row" v-if="config.mousewheelAction === 'zoom'">
        <div class="rowItem">
          <span class="name">{{ $t('setting.mousewheelZoomActionReverse') }}</span>
          <el-switch
            v-model="config.mousewheelZoomActionReverse"
            @change="
              value => {
                updateOtherConfig('mousewheelZoomActionReverse', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.createNewNodeBehavior') }}</span>
          <el-select
            v-model="config.createNewNodeBehavior"
            size="small"
            @change="
              value => {
                updateOtherConfig('createNewNodeBehavior', value)
              }
            "
          >
            <el-option
              v-for="item in createNewNodeBehaviorList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.openRealtimeRenderOnNodeTextEdit') }}</span>
          <el-switch
            v-model="config.openRealtimeRenderOnNodeTextEdit"
            @change="
              value => {
                updateOtherConfig('openRealtimeRenderOnNodeTextEdit', value)
              }
            "
          ></el-switch>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.imgTextMargin') }}</span>
          <el-input-number
            v-model="config.imgTextMargin"
            size="small"
            :min="0"
            @change="
              value => {
                updateOtherConfig('imgTextMargin', value)
              }
            "
          ></el-input-number>
        </div>
      </div>
      <div class="row">
        <div class="rowItem">
          <span class="name">{{ $t('setting.textContentMargin') }}</span>
          <el-input-number
            v-model="config.textContentMargin"
            size="small"
            :min="0"
            @change="
              value => {
                updateOtherConfig('textContentMargin', value)
              }
            "
          ></el-input-number>
        </div>
      </div>
    </div>
  </Sidebar>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessageBox } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useMainStore } from '@/stores'
import { useEventBus } from '@/hooks'
import { storeConfig } from '@/api'
import Sidebar from './Sidebar.vue'
import Color from './Color.vue'

const { t } = useI18n()
const store = useMainStore()
const { isDark, localConfig, configData } = storeToRefs(store)
const { setLocalConfig } = store
const { $on, $off, $emit, $once } = useEventBus()

// Props
const props = defineProps({
  configData: {
    type: Object,
    default: null
  },
  mindMap: {
    type: Object
  }
})

// Refs
const sidebarRef = ref(null)

// Reactive data
const config = reactive({
  openPerformance: false,
  enableFreeDrag: false,
  mousewheelAction: 'zoom',
  mousewheelZoomActionReverse: false,
  createNewNodeBehavior: 'default',
  openRealtimeRenderOnNodeTextEdit: true,
  alwaysShowExpandBtn: false,
  enableAutoEnterTextEditWhenKeydown: true,
  imgTextMargin: 0,
  textContentMargin: 0,
  enableInheritAncestorLineStyle: false
})

const watermarkConfig = reactive({
  show: false,
  onlyExport: false,
  text: '',
  lineSpacing: 100,
  textSpacing: 100,
  angle: 30,
  textStyle: {
    color: '#999',
    opacity: 0.5,
    fontSize: 14
  }
})

const localConfigs = reactive({
  isShowScrollbar: false,
  enableDragImport: false,
  enableAi: false
})

const enableNodeRichText = ref(true)
const updateWatermarkTimer = ref(null)

// Computed
const mousewheelActionList = computed(() => [
  // {
  //   name: t('setting.move'),
  //   value: 'move'
  // },
  // {
  //   name: t('setting.zoom'),
  //   value: 'zoom'
  // }
])

const createNewNodeBehaviorList = computed(() => [
  {
    name: t('setting.default'),
    value: 'default'
  },
  {
    name: t('setting.notActive'),
    value: 'notActive'
  },
  {
    name: t('setting.activeOnly'),
    value: 'activeOnly'
  }
])

// Watch
watch(() => store.activeSidebar, (val) => {
  if (val === 'Setting') {
    sidebarRef.value.show = true
    initConfig()
    initWatermark()
  } else {
    sidebarRef.value.show = false
  }
})

// Lifecycle
onMounted(() => {
  initLoacalConfig()
  $on('toggleOpenNodeRichText', onToggleOpenNodeRichText)
})

onBeforeUnmount(() => {
  $off('toggleOpenNodeRichText', onToggleOpenNodeRichText)
})

// Methods
const initConfig = () => {
  Object.keys(config).forEach(key => {
    if (typeof config[key] === 'object') {
      config[key] = {
        ...(props.mindMap.getConfig(key) || {})
      }
    } else {
      config[key] = props.mindMap.getConfig(key)
    }
  })
}

const initLoacalConfig = () => {
  enableNodeRichText.value = localConfig.value.openNodeRichText
  Object.keys(localConfigs).forEach(key => {
    localConfigs[key] = localConfig.value[key]
  })
}

const initWatermark = () => {
  const config = props.mindMap.getConfig('watermarkConfig')
  ;['text', 'lineSpacing', 'textSpacing', 'angle', 'onlyExport'].forEach(
    key => {
      watermarkConfig[key] = config[key]
    }
  )
  watermarkConfig.show = !!config.text
  watermarkConfig.textStyle = { ...config.textStyle }
}

const updateOtherConfig = (key, value) => {
  props.mindMap.updateConfig({
    [key]: value
  })
  configData.value[key] = value
  storeConfig(configData.value)
  if (
    [
      'alwaysShowExpandBtn',
      'imgTextMargin',
      'textContentMargin',
      'enableInheritAncestorLineStyle'
    ].includes(key)
  ) {
    props.mindMap.reRender()
  }
}

const updateWatermarkConfig = () => {
  clearTimeout(updateWatermarkTimer.value)
  updateWatermarkTimer.value = setTimeout(() => {
    let { show, ...config } = watermarkConfig
    props.mindMap.watermark.updateWatermark({
      ...config
    })
    configData.value.watermarkConfig = props.mindMap.getConfig(
      'watermarkConfig'
    )
    storeConfig(configData.value)
  }, 300)
}

const watermarkShowChange = (value) => {
  if (value) {
    let text =
      watermarkConfig.text || t('setting.watermarkDefaultText')
    watermarkConfig.text = text
  } else {
    watermarkConfig.text = ''
  }
  updateWatermarkConfig()
}

const enableNodeRichTextChange = (e) => {
  ElMessageBox.confirm(
    t('setting.changeRichTextTip'),
    e
      ? t('setting.changeRichTextTip2')
      : t('setting.changeRichTextTip3'),
    {
      confirmButtonText: t('setting.confirm'),
      cancelButtonText: t('setting.cancel'),
      type: 'warning'
    }
  )
    .then(() => {
      props.mindMap.renderer.textEdit.hideEditTextBox()
      setLocalConfig({
        openNodeRichText: e
      })
    })
    .catch(() => {
      enableNodeRichText.value = !enableNodeRichText.value
    })
}

const onToggleOpenNodeRichText = (val) => {
  setLocalConfig({
    openNodeRichText: val
  })
  enableNodeRichText.value = val
}

const updateLocalConfig = (key, value) => {
  setLocalConfig({
    [key]: value
  })
}
</script>

<style lang="less" scoped>
.sidebarContent {
  padding: 20px;
  padding-top: 10px;

  &.isDark {
    .title {
      color: #fff;
    }

    .row {
      .rowItem {
        .name {
          color: hsla(0, 0%, 100%, 0.6);
        }
      }
    }
  }

  .title {
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: rgba(26, 26, 26, 0.9);
    margin-bottom: 10px;
    margin-top: 20px;

    &.noTop {
      margin-top: 0;
    }
  }

  .row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;

    .rowItem {
      display: flex;
      align-items: center;
      margin-bottom: 5px;

      .name {
        font-size: 12px;
        margin-right: 10px;
        white-space: nowrap;
      }

      .block {
        display: inline-block;
        width: 30px;
        height: 30px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        cursor: pointer;
      }
    }
  }
}
</style>
